import {
  getcharts,
  getMaxscore,
  updateScore,
  applogin,
  loginload,
  getnextuser
} from '../../service/login'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: 0,
    maxScore: 0,
    oldMaxScore: 0,
    ground: [],//操场
    rows: 28,
    cols: 22,
    snake: [],
    food: [-1,-1],
    startx: 0,
    starty: 0,
    x: 0,
    y: 0,
    direction: '',
    timer: '',
    life:6,
    lifeadd:[-1,-1],
    modalHidden: true,
    allis1:true,
    uselife:true,
    seed:350,
    url:'',
    userurl:'',
    ispause:false,
    pauseValue:'暂停(长按结束游戏)',
    //排行榜
    charts:[],
    //next用户信息
    userinfo:[],
    current_page:1,
    last_page:'',
    isTopone:true,
    addBoom:[],
    Boomurl:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1590429916584&di=963fb01399595997388a812d57e099a8&imgtype=0&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D3847493163%2C1416440576%26fm%3D214%26gp%3D0.jpg'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getnextuser(1).then(res =>{
     this.setData({
      userinfo:res.data.data,
      last_page:res.data.last_page
     })
     this.initGround(this.data.rows, this.data.cols);
     this.initSnake(3);
     this.creatFood();
     this.move();
    })
    wx.login({
      success: res => {
        if (res.code) {
          //发起网络请求
          applogin(res.code).then(res1=>{
            var openid = res1.data;
            wx.getUserInfo({
              success: res => {
                this.setData({
                  url:res.userInfo.avatarUrl
                })
                loginload(openid,res.userInfo.nickName,res.userInfo.avatarUrl).then(res =>{
                  let maxscore = wx.getStorageSync('maxscore');
                  if (!maxscore){
                    getMaxscore(openid).then(res =>{
                      this.setData({
                        maxScore: res.data[0].Maxscore,
                        oldMaxScore:res.data[0].Maxscore
                      });
                    })
                }
                 
                })
                
              }
            })
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
     
  },
  onShow:function(){
  },
  //初始化操场
  initGround: function (rows, cols) {
    let ground = Array(rows).fill(0).map(item => Array(cols).fill(0));
    this.setData({
      ground: ground
    });
  },
  //初始化蛇
  initSnake: function (len) {
    let snake = this.data.snake;
    let ground = this.data.ground;
    for (let i = 0; i < len; i++) {
      snake.push([0, i]);
      ground[0][i] = 1;
    }ground[0][len-1]=4
    this.setData({
      snake: snake,
      ground: ground
    })
  },
  //生成食物
  creatFood: function () {
    let x = Math.floor(Math.random() * this.data.rows);
    let y = Math.floor(Math.random() * this.data.cols);
    if(x==0){
      x=1
    }else if(y==0){
      y=1
    }else if(x==27){
      x==26
    }else if(y==21){
      y=20
    }
    let food = [x, y];
    let ground = this.data.ground;
    if(ground[x][y]!=0){
      console.log('重复')
      for(var i=0;i<ground.length;i++){
        for(var j=0;j<ground[i].length;j++){
         if(ground[i][j]==0){
           this.creatFood();
           return
         }
         if(ground[27][21]==1){
          clearInterval(this.data.timer);
          this.setData({
            allis1: false
          })
         }
        }
       }
    }else{
      if(this.data.isTopone&&(this.data.score==this.data.userinfo[0].Maxscore||this.data.score==this.data.userinfo[1].Maxscore||this.data.score==this.data.userinfo[2].Maxscore||this.data.score==this.data.userinfo[2].Maxscore)){
        ground[x][y] = 5;
        this.data.userinfo.forEach((item,key) => {
          if(item.Maxscore==this.data.score){
            this.setData({
              userurl:item.avatarUrl
            })
            if(key==2){
              getnextuser(this.data.current_page+1).then(res =>{
                this.setData({
                 current_page:res.data.current_page,
                 userinfo:res.data.data,
                 last_page:res.data.last_page
                })
                if(this.data.current_page==this.data.last_page){
                    this.setData({
                      isTopone:false
                    })
                }
               })
            }
          }
        });
        this.setData({
          food: food,
          ground: ground
        })
      }else{
        ground[x][y] = 2;
        this.setData({
          food: food,
          ground: ground
        })
      }
    }
  },
   //增加生命
   creatLife: function () {
    let x = Math.floor(Math.random() * this.data.rows);
    let y = Math.floor(Math.random() * this.data.cols);
    if(x==0){
      x=1
    }else if(y==0){
      y=1
    }else if(x==27){
      x==26
    }else if(y==21){
      y=20
    }
    let life = [x, y];
    let ground = this.data.ground;
    if(ground[x][y]!=0){
      for(var i=0;i<ground.length;i++){
        for(var j=0;j<ground[i].length;j++){
         if(ground[i][j]==0){
           this.creatLife()
           return
         }
         if(ground[27][21]==1){
          clearInterval(this.data.timer);
          this.setData({
            allis1: false
          })
         }
        }
       }
    }else{
      ground[x][y] = 3;
      this.setData({
        lifeadd: life,
        ground: ground
      })
    }
  },
//炸弹
creatBoom: function () {
  let x = Math.floor(Math.random() * this.data.rows);
  let y = Math.floor(Math.random() * this.data.cols);
  if(x==0){
    x=1
  }else if(y==0){
    y=1
  }else if(x==27){
    x==26
  }else if(y==21){
    y=20
  }
  let ground = this.data.ground;
  if(ground[x][y]!=0){
    for(var i=0;i<ground.length;i++){
      for(var j=0;j<ground[i].length;j++){
       if(ground[i][j]==0){
         this.creatBoom()
         return
       }
       if(ground[27][21]==1){
        clearInterval(this.data.timer);
        this.setData({
          allis1: false
        })
       }
      }
     }
  }else{
    ground[x][y] = 6;
    var addBoom = this.data.addBoom;
    addBoom.push([x, y])
    this.setData({
      addBoom,
      ground: ground
    })
  }
},
  //暂停
  pause:function(){
    this.setData({
      ispause:!this.data.ispause
    })
    if(this.data.ispause){
      this.setData({
        pauseValue:'开始'
      })
      clearInterval(this.data.timer);
      var oldMaxScore = this.data.oldMaxScore;
      if(oldMaxScore<this.data.maxScore){
        updateScore(app.globalData.openid,this.data.maxScore).then(res =>{
         console.log(res)
        })
      }
    }else{
      this.setData({
        pauseValue:'暂停(长按结束游戏)'
      })
      this.move();
    }
  },
  touchStart: function (e) {
    let startx = e.touches[0].pageX;
    let starty = e.touches[0].pageY;
    this.setData({
      startx: startx,
      starty: starty
    })
  },
  touchMove: function (e) {
    this.setData({
      x: e.touches[0].pageX - this.data.startx,
      y: e.touches[0].pageY - this.data.starty
    });
  },
  touchEnd: function () {
    let x = this.data.x, y = this.data.y;
    let direction = '';
    if (Math.abs(x) > Math.abs(y) && x > 0) {
      direction = 'right';
      // console.log('right');
    } else if (Math.abs(x) > Math.abs(y) && x < 0) {
      direction = 'left';
      // console.log('left');
    } else if (Math.abs(x) < Math.abs(y) && y < 0) {
      direction = 'up';
      // console.log('up');
    } else {
      direction = 'down';
      // console.log('down');
    }
    this.setData({
      direction: direction
    })
  },
  //计分器
  storeScore: function () {
    if (this.data.maxScore < this.data.score) {
      this.setData({
        maxScore: this.data.score
      })
      wx.setStorageSync('maxScore', this.data.maxScore)
    }
  },
  //移动函数
  move: function () {
    let that = this;
      this.data.timer = setInterval(function () {
        that.changeDir(that.data.direction);
      }, this.data.seed)
  },
  //贪吃蛇位置改变
  changeDir: function (dir) {
    if(dir){
      let ground = this.data.ground;
      let food = this.data.food;
      let lifeadd = this.data.lifeadd;
      if(food!=[-1,-1]){
        if(food[0]!=-1){
          if(ground[food[0]][food[1]]==0){
            ground[food[0]][food[1]]=2
          }
        }
      }else if(lifeadd!=[-1,-1]){
        if(lifeadd[0]!=-1){
          if(ground[lifeadd[0]][lifeadd[1]]==0){
            ground[lifeadd[0]][lifeadd[1]]=3
          }
        }
      }
      var snake = this.data.snake;
      var len = snake.length;
      var snakeHead = snake[len - 1], snakeTail = snake[0];
      
      ground[snakeTail[0]][snakeTail[1]] = 0;
      for (var i = 0; i < len - 1; i++) {
        snake[i] = snake[i + 1];
      }
      var x = snakeHead[0], y = snakeHead[1];
      switch (dir) {
        case 'left':
          y--;
          break;
        case 'right':
          y++;
          break;
        case 'up':
          x--;
          break;
        case 'down':
          x++;
          break;
      };
      if ( x < 0 || x >= this.data.rows ||  y < 0 ||  y >= this.data.cols) {
        if(this.data.life > 0){
          this.setData({
            direction:'',
            life:this.data.life-1
          })
        }else{
          clearInterval(this.data.timer);
          this.setData({
            modalHidden: false
          })
        }
      }else{
        snake[len - 1] = [x, y];
        this.checkGame(snakeTail);
        for (var i = 1; i < len; i++) {
          ground[snake[i][0]][snake[i][1]] = 1;
        }
        ground[x][y]=4
        this.setData({
          snake: snake,
          ground: ground
        })
      }
    }
  },
  //出局或者吃到格子条件判断
  checkGame: function (snakeTail) {
    let snake = this.data.snake;
    let len = snake.length;
    let snakeHead = snake[len - 1];
    
    if (snakeHead[0] == this.data.food[0] && snakeHead[1] == this.data.food[1]) {
      snake.unshift(snakeTail)
      var seed = this.data.seed;
      if(seed>250){
        seed-=20
      }else if(seed>180){
        seed-=5
      }
      this.setData({
        score: this.data.score + 10,
        food:[-1,-1],
        seed
      });
      clearInterval(this.data.timer);
      this.move();
      this.storeScore();
      var num=Math.floor(Math.random()*10+1);
      if(num==5){
        this.creatLife();
      }else{
        this.creatFood();
      }
      //根据分数增加炸弹数量。第一个炸弹出现在100分
      if(this.data.score>=100){
        console.log('this.data.score>=100')
        if(this.data.score%100===0){
          console.log('this.data.score%100===0')
          this.data.addBoom.forEach((item,key)=>{
            console.log('取消炸弹')
          var ground = this.data.ground;
          if(ground[item[0]][item[1]] ==6){
            ground[item[0]][item[1]] =0;
            this.setData({
              ground
            })
          }
        });
        this.setData({
          addBoom:[]
        })
          var num = this.data.score/100;
          for(var i=1;i<=num;i++){
            console.log('Boom create')
              this.creatBoom();
              this.creatBoom();
          }
        }
      }
    }
    if (snakeHead[0] == this.data.lifeadd[0] && snakeHead[1] == this.data.lifeadd[1]) {
      this.setData({
        life: this.data.life + 1,
        lifeadd:[-1,-1]
      });
      var num=Math.floor(Math.random()*10+1);
      if(num==5){
        this.creatLife();
      }else{
        this.creatFood();
      }
    }
    this.data.addBoom.forEach((item,key)=>{
      if (snakeHead[0] ==item[0] && snakeHead[1] == item[1]) {
        this.setData({
          animation: 'shake'
        })
        console.log(1)
        var that = this;
        setTimeout(function() {
          that.setData({
            animation: ''
          })
        }, 2000)
        if(this.data.life > 0){
          this.setData({
            life:this.data.life-1
          })
        }else{
          clearInterval(this.data.timer);
          this.setData({
            modalHidden: false
          })
        }
      }
    });
  },
  uselife:function(){
    this.setData({
      direction:''
    })
  },
  //清空
  modalChange: function () {
    //更新分数
    clearInterval(this.data.timer);
    var oldMaxScore = this.data.oldMaxScore;
          if(oldMaxScore<this.data.maxScore){
            updateScore(app.globalData.openid,this.data.maxScore).then(res =>{
             console.log(res)
            })
          }
    this.setData({
      pauseValue:'暂停(长按结束游戏)',
      ispause:false,
      score: 0,
      snake: [],
      ground: [],
      food: [],
      modalHidden: true,
      direction: '',
      seed:350,
      life:6
    });
    this.onLoad();
  },

  //排行榜
  showModal(e) {
    getcharts().then(res =>{
      this.setData({
        modalName: e.currentTarget.dataset.target,
        charts:res
      })
    })
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
})